﻿using UnityEngine;

struct AreaRect
{
    public int minX { get; private set; }
    public int minY { get; private set; }
    public int maxX { get; private set; }
    public int maxY { get; private set; }
    public int width { get; private set; }
    public int height { get; private set; }

    public int GetXBy01(float x01)
    {
        return Mathf.RoundToInt(Mathf.Lerp(minX, maxX, x01));
    }

    public int GetYBy01(float y01)
    {
        return Mathf.RoundToInt(Mathf.Lerp(minY, maxY, y01));
    }

    public Vector2Int GetBy01(Vector2 v01)
    {
        return GetBy01(v01.x, v01.y);
    }

    public Vector2Int GetBy01(float x, float y)
    {
        return new Vector2Int(GetXBy01(x), GetYBy01(y));
    }

    public float Get01ByX(int x)
    {
        return (float)(x - minX) / (maxX - minX);
    }

    public float Get01ByY(int y)
    {
        return (float)(y - minY) / (maxY - minY);
    }

    public Vector2 Get01(Vector2Int vi)
    {
        return Get01(vi.x, vi.y);
    }

    public Vector2 Get01(int x, int y)
    {
        return new Vector2(Get01ByX(x), Get01ByY(y));
    }

    public AreaRect(RectTransform rt)
    {
        var root = rt.GetComponentInParent<Canvas>().transform;

        var min = root.TransformPoint(rt.offsetMin);
        var max = root.TransformPoint(rt.offsetMax);
        this = new AreaRect(min, max);
    }

    public AreaRect(Vector2 min, Vector2 max)
    {
        minX = Mathf.RoundToInt(min.x);
        minY = Mathf.RoundToInt(min.y);
        maxX = Mathf.RoundToInt(max.x);
        maxY = Mathf.RoundToInt(max.y);
        width = maxX - minX + 1;
        height = maxY - minY + 1;
    }
}